require('dotenv').config();
const express = require('express');
const path = require('path');
const cors = require('cors');
const { testConnection } = require('./config/db');

// 路由导入
const userRouter = require('./routes/users');
const bookRouter = require('./routes/book');
const bookshelfRouter = require('./routes/bookshelf');
const cartRouter = require('./routes/cart');
const borrowRouter = require('./routes/borrow');
const announcementRouter = require('./routes/announcement');
const notificationRouter = require('./routes/notification');
const renewApplicationRouter = require('./routes/renewApplication');
const adminLogRouter = require('./routes/adminLog');
const reservationRouter = require('./routes/reservation');
const adminUserRouter = require('./routes/adminUser');
const adminBorrowRouter = require('./routes/adminBorrow');

const errorHandler = require('./middleware/errorHandler');

const app = express();
const PORT = process.env.PORT || 3001;

// 中间件
app.use(cors({
  origin: process.env.NODE_ENV === 'production' ? false : true,
  credentials: true
}));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务（用于访问上传的封面图片）
app.use('/uploads', express.static(path.join(__dirname, 'public/uploads')));
app.use(express.static(path.join(__dirname, 'public')));

// 请求日志中间件
if (process.env.NODE_ENV === 'development') {
  const morgan = require('morgan');
  app.use(morgan('dev'));
}

// 路由
app.use('/api/user', userRouter);
app.use('/api/books', bookRouter);
app.use('/api/bookshelf', bookshelfRouter);
app.use('/api/cart', cartRouter);
app.use('/api/borrow', borrowRouter);
app.use('/api/announcements', announcementRouter);
app.use('/api/notifications', notificationRouter);
app.use('/api/renew-applications', renewApplicationRouter);
app.use('/api/admin-logs', adminLogRouter);
app.use('/api/reservations', reservationRouter);
app.use('/api/admin/users', adminUserRouter);
app.use('/api/admin/borrow', adminBorrowRouter);

// 健康检查接口
app.get('/health', (req, res) => {
  res.json({ 
    code: 200, 
    message: '服务运行正常',
    timestamp: new Date().toISOString()
  });
});

// 404 处理
app.use((req, res) => {
  res.status(404).json({ code: 404, msg: '接口不存在' });
});

// 错误处理中间件
app.use(errorHandler);

// 测试数据库连接并启动服务
testConnection()
  .then(() => {
    app.listen(PORT, () => {
      console.log(`🚀 服务运行在 http://localhost:${PORT}`);
      console.log(`📚 图书管理系统后端服务已启动`);
      console.log(`💾 使用 MySQL2 原生查询`);
    });
  })
  .catch(err => {
    console.error('❌ 数据库连接失败:', err);
    process.exit(1);
  });